package com.tl.juc.c2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class C1_CreateThreadPool {
    public static void main(String[] args) throws InterruptedException {
        class Task implements Runnable {

            @Override
            public void run() {
                log.info("\t 办理业务");
            }
        }
        Task task = new Task();

        // 固定大小的线程池
         ExecutorService threadPool = Executors.newFixedThreadPool(5);// 一个饭店，五张桌子
        // ExecutorService threadPool = Executors.newSingleThreadExecutor();// 一个饭店，一张桌子
        // ExecutorService  threadPool = Executors.newCachedThreadPool(); // 一个饭店，可以动态的加桌子
        // 延迟加载
        // ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
        // 十个顾客的请求
        try {
            for (int i=0;i<10;i++){
                threadPool.execute(task);
                // threadPool.schedule(task,5, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            // 不会立马停止正在执行的线程，会等待所有任务执行完毕以后才彻底关闭
            //threadPool.shutdown();
            // 主线程等待一下线程池关闭，等待所有线程执行完毕
            threadPool.shutdownNow();
            // 主线程等待一下线程池关闭，等待线程池中所有线程是否执行完呢
            threadPool.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);


            // 判断线程池是否真正”终止"了，并且代表线程池也已经执行完毕
            System.out.println(threadPool.isTerminated());
        }
    }
}
